package com.example.ai.uploadImage;

import java.util.*;
import java.util.regex.*;

public class AdaptiveSceneParser {
    private LinkedHashMap<String, String> sceneMap = new LinkedHashMap<>();

    /**
     * 自适应解析各种格式的场景文本
     */
    public LinkedHashMap<String, String> parseScenes(String text) {
        sceneMap.clear();

        // 多种场景标题模式
        String[] scenePatterns = {
                "\\*\\*场景\\d+：",                    // **场景1：
                "场景\\d+：",                         // 场景1：
                "第\\d+场景：",                       // 第1场景：
                "Scene\\d+：",                       // Scene1：
                "【场景\\d+】",                       // 【场景1】
                "场景\\d+\\s*[-–—]\\s*"              // 场景1 -
        };

        // 构建统一的正则表达式
        String combinedPattern = String.join("|", scenePatterns);
        Pattern pattern = Pattern.compile(combinedPattern);

        // 按场景分割文本
        String[] scenes = pattern.split(text);

        // 提取场景标题
        List<String> sceneTitles = new ArrayList<>();
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            sceneTitles.add(matcher.group().trim());
        }

        // 配对场景标题和内容
        int sceneIndex = 1;
        for (int i = 0; i < scenes.length; i++) {
            if (scenes[i].trim().isEmpty()) continue;

            String sceneTitle = (i > 0 && i - 1 < sceneTitles.size()) ?
                    sceneTitles.get(i - 1) : "场景" + sceneIndex;
            String sceneContent = scenes[i].trim();

            // 规范化场景键名
            String normalizedKey = normalizeSceneKey(sceneTitle, sceneIndex);
            sceneMap.put(normalizedKey, sceneContent);
            sceneIndex++;
        }

        return new LinkedHashMap<>(sceneMap);
    }

    /**
     * 规范化场景键名
     */
    private String normalizeSceneKey(String rawTitle, int index) {
        // 提取数字
        Pattern numPattern = Pattern.compile("\\d+");
        Matcher matcher = numPattern.matcher(rawTitle);
        if (matcher.find()) {
            return "场景" + matcher.group();
        }
        return "场景" + index;
    }

    /**
     * 更智能的解析方法 - 基于行扫描
     */
    public LinkedHashMap<String, String> parseSmart(String text) {
        sceneMap.clear();

        String[] lines = text.split("\n");
        StringBuilder currentScene = new StringBuilder();
        String currentSceneKey = null;
        int sceneCounter = 1;

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;

            // 检测场景开始
            if (isSceneStart(line)) {
                // 保存上一个场景
                if (currentSceneKey != null && currentScene.length() > 0) {
                    sceneMap.put(currentSceneKey, currentScene.toString().trim());
                }

                // 开始新场景
                currentSceneKey = extractSceneKey(line, sceneCounter);
                currentScene = new StringBuilder();
                sceneCounter++;
            } else if (currentSceneKey != null) {
                // 添加到当前场景内容
                currentScene.append(line).append("\n");
            }
        }

        // 保存最后一个场景
        if (currentSceneKey != null && currentScene.length() > 0) {
            sceneMap.put(currentSceneKey, currentScene.toString().trim());
        }

        return new LinkedHashMap<>(sceneMap);
    }

    /**
     * 判断是否是场景开始行
     */
    private boolean isSceneStart(String line) {
        String[] sceneKeywords = {
                "场景1", "场景2", "场景3", "场景4", "场景5", "场景6",
                "Scene1", "Scene2", "Scene3", "Scene4", "Scene5", "Scene6",
                "第1场景", "第2场景", "第3场景", "第4场景", "第5场景", "第6场景"
        };

        for (String keyword : sceneKeywords) {
            if (line.contains(keyword)) {
                return true;
            }
        }

        // 使用正则匹配
        return line.matches(".*场景\\d+.*") || line.matches(".*Scene\\d+.*");
    }

    /**
     * 提取场景键名
     */
    private String extractSceneKey(String line, int defaultIndex) {
        // 尝试提取数字
        Pattern pattern = Pattern.compile("场景(\\d+)");
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            return "场景" + matcher.group(1);
        }

        pattern = Pattern.compile("Scene(\\d+)");
        matcher = pattern.matcher(line);
        if (matcher.find()) {
            return "场景" + matcher.group(1);
        }

        return "场景" + defaultIndex;
    }

    /**
     * 获取所有场景
     */
    public LinkedHashMap<String, String> getAllScenes() {
        return new LinkedHashMap<>(sceneMap);
    }

    /**
     * 获取指定场景
     */
    public String getScene(String sceneKey) {
        return sceneMap.get(sceneKey);
    }

    public String getScene(int sceneNumber) {
        return sceneMap.get("场景" + sceneNumber);
    }

    /**
     * 获取场景数量
     */
    public int getSceneCount() {
        return sceneMap.size();
    }

    /**
     * 打印解析结果
     */
    public void printResult() {
        System.out.println("解析结果：");
        System.out.println("共找到 " + sceneMap.size() + " 个场景");
        System.out.println("=" .repeat(50));

        for (Map.Entry<String, String> entry : sceneMap.entrySet()) {
            System.out.println("【" + entry.getKey() + "】");
            // 只显示前200个字符预览
            String preview = entry.getValue();
            if (preview.length() > 200) {
                preview = preview.substring(0, 200) + "...";
            }
            System.out.println(preview);
            System.out.println("-".repeat(40));
        }
    }
}
